﻿using ErrorOr;
using Gym.Application.Common.Interfaces;
using Gym.Domain.SessionAggregate;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gym.Application.Gyms.Queries.ListSessions
{
    public class ListSessionsQueryHandler : IRequestHandler<ListSessionsQuery, ErrorOr<List<Session>>>
    {
        private readonly ISubscriptionsRepository _subscriptionsRepository;
        private readonly IGymsRepository _gymsRepository;
        private readonly ISessionsRepository _sessionsRepository;

        public ListSessionsQueryHandler(ISubscriptionsRepository subscriptionsRepository, IGymsRepository gymsRepository, ISessionsRepository sessionsRepository)
        {
            _subscriptionsRepository = subscriptionsRepository;
            _gymsRepository = gymsRepository;
            _sessionsRepository = sessionsRepository;
        }

        public async Task<ErrorOr<List<Session>>> Handle(ListSessionsQuery request, CancellationToken cancellationToken)
        {
            var subscription = await _subscriptionsRepository.GetByIdAsync(request.SubscriptionId);
            if (subscription is null)
            {
                return Error.NotFound(description: "没有找到订阅信息");
            }

            if(!subscription.HasGym(request.GymId))
            {
                return Error.NotFound(description: "没有找到该健身房信息");
            }

            if (!await _gymsRepository.ExistsAsync(request.GymId))
            {
                return Error.NotFound(description: "没有找到该健身房信息");
            }

            return await _sessionsRepository.ListByGymIdAsync(request.GymId, request.StartDateTime, request.EndDateTime, request.Categories);
        }
    }
}
